var config = require("../../../config.js")
var util = require("../../../utils/MD5.js")
var goodsControllor = require("../../../utils/goodsControllor.js");
var g = getApp().globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mebInfo: null,
    pageIndex: 1,
    pageSize: 20,
    keywords: "",
    hasMember: false,
    showDialog: false,
    showOpt: false,
    opInfo: {},
    ShopNo: "",
    classify: [],
    activeItem: 0,
    pageindex: 1,
    mebno: 0,
    dialogType: 0,
    currentGoodsNum: 0,
    zpid: 54,
    Remarks: [],
    goodsList: [],
    resultList: [],
    totalNum: 0,
    totalPrice: 0,
    openOrder: true,
    showInput: false,
    ztInfo: {
      C_CODE: "34234",
      C_ZPNAME: "佳人有约",
      N_CID: 361,
      RegionName: "娱乐区",
      TableName: "佳人有约",
    },
    totalPage: 0,
    stateClass: "state1",
    gcode: "",
    showCart: false,
    isScanCode: false, // 是否扫条码
  },

  onLoad: function(options) {
    this.setData({
      version: g.version,
    })
    if (this.data.openOrder) {
      
    }
    if (options.mebno) {
      this.data.mebno = options.mebno;
    }
  },
    onShow: function () {
        if (!this.data.isScanCode){
            this.setData({
                goodsList: [],
                totalPrice: 0,
                resultList: [],
                activeItem: 0,
                totalNum: 0
            })
        }else{
            this.setData({ 
                isScanCode: false,
                goodsList: [],
            })
        }
        wx.removeStorage({
            key: 'result-list',
        })
        wx.removeStorage({
            key: 'mebInfo',
        })
        if (!g.scan) {
            wx.getStorage({
                key: 'OP_INFO',
                success: res => {
                    res.data.c_headimg = config.FilePath + res.data.c_headimg
                    this.setData({
                        opInfo: res.data,
                    })
                    wx.getStorage({
                        key: 'C_SHOP_NO',
                        success: rs => {
                            this.data.ShopNo = rs.data;
                            this.getGoodsClassify();
                            this.getShopInfo();
                            this.getShiftInfo();
                        },
                    })
                },
            })
        } else {
            g.scan = false;
        }
    },

  setTel(ev) {
    this.setData({
      keywords: ev.detail.value
    })
  },

  showCart() {
    this.setData({
      showCart: true,
    })
  },

  hideCart() {
    this.setData({
      showCart: false,
    })
  },

  viewSale() {
    wx.navigateTo({
      url: '/pages/retail/sale-record/sale-record',
    })
  },

  viewWork() {
    wx.navigateTo({
      url: '/pages/retail/work-record/work-record',
    })
  },

  setKeyWords(ev) {
    if (ev.detail.value.length > 0) {
      this.setData({
        gcode: ev.detail.value
      })
    } else {
      this.setData({
        goodsList: []
      })
      this.getGoodsList();
    }
  },

  /**
   * 获取会员列表
   */
  getMenberList() {
    var str = `ShopNo&keywords&gradeId&pageIndex&pageSize=${this.data.ShopNo}*${this.data.keywords}*0*${this.data.pageIndex}*${this.data.pageSize}`;
    var md5 = util.md5(str);
    wx.showLoading({
      title: '',
    })
    var data = {
      bNo: 1204,
      ShopNo: this.data.ShopNo,
      keywords: this.data.keywords,
      gradeId: 0,
      pageIndex: this.data.pageIndex,
      pageSize: this.data.pageSize,
      keytype: -1,
      MD5: md5.toUpperCase()
    };

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        var d = res.data.replace(/\(|\)/g, "");
        var t = JSON.parse(d);
        if (t.mebdt.length > 0) {
          for (var i = 0; i < t.mebdt.length; i++) {
            if (t.mebdt[i].C_MB_NAME.length > 20) {
              t.mebdt[i].C_MB_NAME = t.mebdt[i].C_MB_NAME.substr(0, 20) + "..."
            }
          }
          this.setData({
            keywords: "",
            mebno: t.mebdt[0].C_MB_NO,
          })
          this.getMemberDetail();
        } else {
          wx.showModal({
            title: '提示',
            content: '抱歉，暂无会员信息',
            showCancel: false,
          })
        }
        wx.hideLoading()
      }
    })
  },

  getMemberDetail() {
    var MD5 = util.md5(`mebno&ShopNo=${this.data.mebno}*${this.data.ShopNo}`).toUpperCase();
    var data = {
      bNo: 301,
      mebno: this.data.mebno,
      ShopNo: this.data.ShopNo,
      MD5,
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        if (res.data.code === "100") {
          if (res.data.member.C_MB_PIC) {
            res.data.member.C_MB_PIC = config.FilePath + res.data.member.C_MB_PIC
          }
          this.setData({
            mebInfo: res.data.member,
            hasMember: true,
          })
        }
      }
    })
  },

  sureMember() {
    wx.removeStorage({
      key: 'result-list',
      success: res => {
        this.setData({
          goodsList: [],
          resultList: [],
          totalNum: 0,
          totalPrice: 0
        })
        this.getGoodsList();
        this.hideMember();
      }
    })
  },

  getShopInfo() {
    var str = util.md5(`ShopNo=${this.data.ShopNo}`).toUpperCase();
    var data = {
      bNo: 203,
      ShopNo: this.data.ShopNo,
      MD5: str,
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        if (res.data.model.c_remark.length > 20) {
          res.data.model.c_remark = res.data.model.c_remark.substr(0, 20) + "..."
        }
        wx.setNavigationBarTitle({
          title: res.data.model.c_name,
        })
        this.setData({
          shopInfo: res.data.model
        })
      }
    })
  },

  def() {},

  hideMember() {
    this.setData({
      showDialog: false,
    })
  },

  showMember() {
    this.setData({
      showDialog: true,
    })
  },

  showOptInfo() {
    this.setData({
      showOpt: true,
    })
  },

  hideOptInfo() {
    this.setData({
      showOpt: false,
    })
  },

  getGoodsClassify() {
    var md5 = util.md5(`ShopNo=${this.data.ShopNo}`).toUpperCase();
    var data = {
      bNo: 3100,
      ShopNo: this.data.ShopNo,
      MD5: md5,
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        for (var i = 0; i < res.data.Result.length; i++) {
          if (res.data.Result[i].CATEGORY_NAME.length > 4) {
            res.data.Result[i].CATEGORY_NAME = res.data.Result[i].CATEGORY_NAME.substr(0, 4) + "..."
          }
          res.data.Result[i].num = 0;
        }
        this.setData({
          cid: res.data.Result[0].ID,
          classify: res.data.Result,
        })
        this.getGoodsList();
      }
    })
  },

  changeClassify(ev) {
    this.setData({
      goodsList: [],
      pageindex: 1,
      activeItem: ev.currentTarget.dataset.d,
      cid: ev.currentTarget.dataset.i,
    }, () => {
      this.getGoodsList();
    })
  },

  loadGoods() {
    if (this.data.gcode == "") {
      if (this.data.pageindex < this.data.totalPage) {
        this.data.pageindex++;
        this.getGoodsList();
      }
    }
  },

  openScan() {
    this.setData({ isScanCode: true })
    wx.scanCode({
      success: res => {
        this.data.gcode = res.result;
        g.scan = true;
        this.searchGoods();
      }
    })
  },
  // 扫条码、搜索
  searchGoods() {
    if (!this.data.gcode) {
      wx.showModal({
        title: '提示',
        content: '请输入搜索关键词',
        showCancel: false,
      })
      return;
    }
    console.log(this.data.resultList)
    this.setData({
      goodsList: [],
    })
    wx.showLoading({
      title: '',
    })
    var MD5 = util.md5(`ShopNo&gcode&MebNo=${this.data.ShopNo}*${this.data.gcode}*${this.data.mebno}`).toUpperCase();
    var data = {
      bNo: 4010,
      ShopNo: this.data.ShopNo,
      gcode: this.data.gcode,
      MebNo: this.data.mebno,
      MD5,
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        wx.hideLoading()
        if (res.data.code == "100") {
          var arr = [];
          var noData = false;
          for (var i = 0; i < res.data.dtResult.length; i++) {
            if (res.data.dtResult[i].GOODS_NAME.length > 24) {
              res.data.dtResult[i].GOODS_NAME = res.data.dtResult[i].GOODS_NAME.substr(0, 24) + "..."
            }

            if (res.data.dtResult[i].C_MAINPICTURE) {
              res.data.dtResult[i].C_MAINPICTURE = config.FilePath + res.data.dtResult[i].C_MAINPICTURE;
            }

            res.data.dtResult[i].N_NUM = 0;
          }

          if (res.data.dtResult.length < 10) {
            noData = true;
          }
          this.setData({
            goodsList: res.data.dtResult
          })
            console.log(this.data.resultList)
        }
      }
    })
  },

  getGoodsList() {
    wx.showLoading({
      title: '',
      mask: true,
    })
    var str = `ShopNo&pageindex&pagesize&CateId=${this.data.ShopNo}*${this.data.pageindex}*10*${this.data.cid}`;
    var md5 = util.md5(str);
    var data = {
      bNo: "4005",
      pageindex: this.data.pageindex,
      pagesize: 10,
      mebno: this.data.mebno,
      CateId: this.data.cid,
      ShopNo: this.data.ShopNo,
      MD5: md5.toUpperCase()
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        wx.hideLoading()
        if (this.data.totalPage == 0) {
          this.data.totalPage = res.data.totalPage;
        }
        var arr = [];
        var noData = false;
        for (var i = 0; i < res.data.dtResult.length; i++) {
          if (res.data.dtResult[i].GOODS_NAME.length > 20) {
            res.data.dtResult[i].GOODS_NAME = res.data.dtResult[i].GOODS_NAME.substr(0, 20) + "..."
          }

          if (res.data.dtResult[i].C_MAINPICTURE) {
            res.data.dtResult[i].C_MAINPICTURE = config.FilePath + res.data.dtResult[i].C_MAINPICTURE;
          }
          
          res.data.dtResult[i].N_NUM = 0;
          this.data.goodsList.push(res.data.dtResult[i]);
        }

        if (res.data.dtResult.length < 10) {
          noData = true;
        }

        this.setData({
          goodsList: this.data.goodsList,
          noData
        })

        wx.hideLoading()
      }
    })
  },

  showSpec(ev) {
    wx.showLoading({
      title: '',
      mask: true,
    })
    this.data.Spv1 = 0;
    this.data.Spv2 = 0;
    this.data.Spv3 = 0;
    this.data.currentGoodsIndex = ev.currentTarget.dataset.t;
    this.setData({
      currentGoodsNum: ev.currentTarget.dataset.d.N_NUM || 0,
      C_GoodsRemark: "",
    })
    goodsControllor.getGoodsDetail({
      gid: ev.currentTarget.dataset.i,
      ShopNo: this.data.ShopNo,
      mebno: this.data.mebno,
    }, data => {
      wx.hideLoading()
      this.data.GbId = data.goods[0].N_GB_ID
      data.goods[0].C_MAINPICTURE = config.FilePath + data.goods[0].C_MAINPICTURE;
      this.filterLvgg(data.goods[0].SPECIFICATION, data.lvgg);
      data.goods[0].currentPracitice = null;
      data.goods[0].Batchings = null;
      this.data.goodsList[ev.currentTarget.dataset.t].GOODS_CODE = data.goods[0].GOODS_CODE;
      var showInput = false;
      if (ev.currentTarget.dataset.d.n_iscz) {
        showInput = true;
        data.goods[0].n_iscz = 1;
      }
      this.setData({
        currentGoods: data.goods[0],
        currentAttr: data.lvgg,
        detailCover: true,
        dialogType: 1,
        spec: 1,
        showInput,
      })
    })
  },

  setWeightNumber(ev) {
    this.setData({
      currentGoodsNum: ev.detail.value
    })
  },
  // 加入购物车
  sureGoods() {
      console.log(this.data.currentGoodsNum)
      console.log(this.data.resultList)
    if (this.data.currentGoodsNum > 0) {
      var flag = false;
      this.data.currentGoods.cid = this.data.cid;
      this.data.goodsList[this.data.currentGoodsIndex].N_NUM = this.data.currentGoodsNum;
      this.data.goodsList[this.data.currentGoodsIndex].C_UnitName = this.data.currentGoods.C_UnitName
      if (this.data.resultList.length > 0) {
        for (var i = 0; i < this.data.resultList.length; i++) {
          if (this.data.resultList[i].ID == this.data.currentGoods.ID) {
            this.data.resultList[i] = this.data.goodsList[this.data.currentGoodsIndex];
            flag = true;
            break;
          }
        }

        if (!flag) {
          this.data.resultList.push(this.data.goodsList[this.data.currentGoodsIndex])
        }
      } else {
        this.data.resultList.push(this.data.goodsList[this.data.currentGoodsIndex])
      }
      this.setData({
        resultList: this.data.resultList,
        goodsList: this.data.goodsList,
      })

      this.getTotalInfo();
    }
    this.hideDialog();
  },

  clearList() {
    for (var i = 0; i < this.data.goodsList.length; i++) {
      this.data.goodsList[i].N_NUM = 0;
    }
    this.setData({
      goodsList: this.data.goodsList,
      resultList: [],
      totalNum: 0,
      totalPrice: 0,
      showCart: false,
    }) 
  },

  getTotalInfo() {
    var totalNum = 0;
    var totalPrice = 0;
    for (var i = 0; i < this.data.resultList.length; i++) {
      if (this.data.resultList[i].currentPractice) {
        totalPrice += this.data.resultList[i].currentPractice.Practice_Price;
      }

      if (this.data.resultList[i].Batchings) {
        for (var j = 0; j < this.data.resultList[i].Batchings.length; j++) {
          if (this.data.resultList[i].Batchings[j].checked) {
            totalPrice += this.data.resultList[i].Batchings[j].Batching_Price * this.data.resultList[i].Batchings[j].num;
          }
        }
      }

      if (this.data.resultList[i].N_NUM > 0) {
        totalNum++;
      }
      totalPrice += this.data.resultList[i].SALE_PRICE * this.data.resultList[i].N_NUM;
    }

    totalPrice = parseFloat(totalPrice).toFixed(2)

    this.setData({
      totalNum,
      totalPrice,
    })
  },

  /**
   * 筛选规格
   */
  filterLvgg(t, lvgg) {
    // 切出当前商品的规格
    var attr = t.split(" ");
    // 去掉多余的数组
    attr.pop();
    var gAttr = [];
    // 筛选规格，只留下规格值
    for (var i = 0; i < attr.length; i++) {
      gAttr.push(attr[i].split(":")[1]);
    }
    // 判断哪个规格是选中状态
    for (var i = 0; i < gAttr.length; i++) {
      for (var j = 0; j < lvgg[i].SpvList.length; j++) {
        if (lvgg[i].SpvList[j].C_SPE_VALUE == gAttr[i]) {
          lvgg[i].SpvList[j].checked = true;
          switch (i) {
            case 0:
              this.data.Spv1 = lvgg[i].SpvList[j].N_SPV_ID;
              break;
            case 1:
              this.data.Spv2 = lvgg[i].SpvList[j].N_SPV_ID;
              break;
            case 2:
              this.data.Spv3 = lvgg[i].SpvList[j].N_SPV_ID;
              break;
          }
        }
      }
    }

    // 设置规格值
    this.setData({
      currentAttr: lvgg,
    })
  },

  /**
   * 当前菜品的增加
   */
  plus() {
    this.data.currentGoodsNum++;
    this.setData({
      currentGoodsNum: this.data.currentGoodsNum
    })
  },

  /**
   * 商品数量相减
   */
  minus() {
    this.data.totalNum--;
    if (this.data.currentGoodsNum > 0) {
      this.data.currentGoodsNum--;
      this.data.goodsList[this.data.currentGoodsIndex].N_NUM--;
      this.setData({
        currentGoodsNum: this.data.currentGoodsNum,
        totalNum: this.data.totalNum,
        goodsList: this.data.goodsList,
      })
    } else {
      this.data.goodsList[this.data.currentGoodsIndex].N_NUM = 0;
      this.setData({
        currentGoodsNum: 0,
        totalNum: this.data.totalNum,
        goodsList: this.data.goodsList,
      })
    }
  },

  /**
   * 
   */
  changeSpecTab(ev) {
    this.setData({
      spec: ev.currentTarget.dataset.i
    })
  },

  sureOrder() {
    if (this.data.resultList.length > 0) {
      wx.setStorage({
        key: 'result-list',
        data: {
          gList: this.data.resultList,
          totalPrice: this.data.totalPrice,
          totalNum: this.data.totalNum
        },
        success: res => {
          wx.setStorage({
            key: 'mebInfo',
            data: this.data.mebInfo,
            success: () => {
              wx.navigateTo({
                url: '/pages/retail/submitGoods/submitGoods',
              })
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请先添加商品',
        showCancel: false,
      })
    }
  },

  /**
   * 切换规格
   */
  changeAttr(ev) {
    var index = ev.currentTarget.dataset.i;
    var sIndex = ev.currentTarget.dataset.si;

    switch (index) {
      case 0:
        this.data.Spv1 = this.data.currentAttr[index].SpvList[sIndex].N_SPV_ID;
        break;
      case 1:
        this.data.Spv2 = this.data.currentAttr[index].SpvList[sIndex].N_SPV_ID;
        break;
      case 2:
        this.data.Spv3 = this.data.currentAttr[index].SpvList[sIndex].N_SPV_ID;
        break;
    };

    this.getGoodsDetailAttr()
  },

  /**
   * 获取规格商品
   */
  getGoodsDetailAttr() {
    wx.showLoading({
      title: '',
    })
    goodsControllor.getGoodsDetailAttr({
      GbId: this.data.GbId,
      Spv1: this.data.Spv1,
      Spv2: this.data.Spv2,
      Spv3: this.data.Spv3,
      mebno: this.data.mebno,
      ShopNo: this.data.ShopNo
    }, data => {
      // 筛选规格，判断选中规格
      this.filterLvgg(data.goods[0].SPECIFICATION, data.lvgg);
      data.goods[0].C_MAINPICTURE = config.FilePath + data.goods[0].C_MAINPICTURE;
      this.setData({
        currentGoods: data.goods[0]
      })
      wx.hideLoading()
    })
  },

  getShiftInfo() {
    var MD5 = util.md5(`ShopNo&opid&opName=${this.data.ShopNo}*${this.data.opInfo.n_ss_id}*${this.data.opInfo.c_name}`).toUpperCase();
    var data = {
      bNo: 4106,
      ShopNo: this.data.ShopNo,
      opid: this.data.opInfo.n_ss_id,
      opName: this.data.opInfo.c_name,
      MD5,
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        this.setData({
          shift: res.data.Shift,
        })
      }
    })
  },

  jb() {
    wx.showLoading({
      title: '交班中',
    })
    var MD5 = util.md5(`ShopNo&data=${this.data.ShopNo}*${JSON.stringify(this.data.shift)}`).toUpperCase();
    var data = {
      bNo: 4107,
        data: JSON.stringify(this.data.shift),
      ShopNo: this.data.ShopNo,
      MD5,
    };
    console.log(data)

    wx.request({
      url: config.requestUrl,

      method: "POST",
      header: { "Content-Type": "application/x-www-form-urlencoded" },

      data,
      success: res => {
        if (res.data.Result == "1") {
          this.setData({
            hideOptInfo: false,
          })
          wx.showToast({
            title: '交班成功！',
            duration: 2000,
            success: res => {
              wx.removeStorage({
                key: 'OP_INFO',
                success: () => {
                  setTimeout(() => {
                    wx.redirectTo({
                      url: '/pages/login/login',
                    })
                  }, 2000)
                },
              })
            }
          })
        }
      }
    })
  },

  logOut() {
    wx.showModal({
      title: '提示',
      content: '确认退出当前账号吗？',
      success: res => {
        if (res.confirm) {
          wx.removeStorage({
            key: 'OP_INFO',
            success: res => {
              wx.redirectTo({
                url: '/pages/login/login',
              })
            },
          })
        }
      }
    })
  },

  def() {

  },

  hideDialog() {
    this.setData({
      dialogType: 0,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
})